package logic

import (
	"context"
	"errors"
	"shop-ease/internal/cache"
	"shop-ease/internal/mysql"

	"shop-ease/shopRpc/internal/svc"
	"shop-ease/shopRpc/shopRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductAddLogic {
	return &ProductAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductAddLogic) ProductAdd(in *shopRpc.ProductAddRequest) (*shopRpc.ProductAddResponse, error) {
	// 商品添加
	var product mysql.Product
	//err := product.FindProductByName(mysql.DB, in.Name)
	//if err != nil {
	//	return nil, errors.New("该商品已存在")
	//}
	product = mysql.Product{
		Name:   in.Name,
		Price:  float64(in.Price),
		Stock:  in.Stock,
		Img:    in.Img,
		Status: in.Status,
	}
	err := product.ProductAdd(mysql.DB)
	if err != nil {
		return nil, errors.New("商品添加失败")
	}
	//添加虚拟缓存
	cache.SyncVirtualStock(int64(product.ID), int(in.Stock))
	return &shopRpc.ProductAddResponse{
		Success: true,
		Message: "商品添加成功",
	}, nil
}
